<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\facade\OssBackup;
use app\common\model\Logs;
use app\common\model\Statistics;

class Callback
{

    /**
     * @return void
     * 自动备份
     */
    public function autoOssBackup()
    {
        try {
            $route = 'callback/autoOssBackup.log';
            $result = \addons\OssBackup\facade\OssBackup::auto();
            Logs::write($route, json_encode($result));
        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
        }
    }

    /**
     * @return void
     * 更新统计
     */
    public function statistics()
    {
        Statistics::_timing();
    }

    public function order_release()
    {
        \addons\V2\admin\model\Order::order_release();
    }



    public function alipayCallback()
    {
        try {
            $route = 'callback/alipayCallback.log';
            $pay = \AliPay\App::instance(config('pay')['alipay']);
            $data = $pay->notify();
            if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                // @todo 更新订单状态，支付完成

                Logs::write($route, '订单支付成功');
                return 'SUCCESS';
            } else {
                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败:' .json_encode($data));

            }
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());
        }
    }


    public function wechatCallback()
    {
        try {
            $route = 'callback/wechatCallback.log';
            $wechat = \WeChat\Pay::instance(config('pay')['wechat']);
            $data = $wechat->getNotify();
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 更新订单状态，支付完成


                // 返回接收成功的回复
                Logs::write($route, '订单支付成功');
                return $wechat->getNotifySuccessReply();
            } else {
                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败：' . json_encode($data));
            }

        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());

        }
    }


}